<template>
  <Navbar>
    <template v-slot:center>用户登录</template>
  </Navbar>

  <div style="margin-top: 50px">
    <div style="text-align: center">
      <van-image
        width="10rem"
        height="10rem"
        fit="contain"
        src="https://img.yzcdn.cn/vant/cat.jpeg"
      />
    </div>
  </div>
  <div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="userInfo.email"
        name="email"
        label="电子邮箱"
        placeholder="请输入电子邮箱"
        :rules="[{ required: true, message: '请填写邮箱号' }]"
      />
      <van-field
        v-model="userInfo.password"
        type="password"
        name="password"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />

      <div style="margin: 16px">
        <!-- 这里直接调用vue内部的router -->
        <div class="link-register" @click="$router.push('/register')">
          立即注册
        </div>
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { reactive } from "vue";
import { useRouter } from "vue-router";
import { Image as VanImage, Form, Field, Button, Notify, Toast } from "vant";
import Navbar from "@/components/common/navbar/NavBar.vue";
import { login } from "@/network/user";
import { useStore } from "vuex";

export default {
  name: "Login",
  setup() {
    // reactive数据就相当于定义state数据
    const userInfo = reactive({
      email: "",
      password: "",
    });

    const router = useRouter();
    const store = useStore();

    const onSubmit = (value) => {
      // 这里userInfo和Form的数据双向绑定了 ，他俩是响应式的
      login(value).then((res) => {
        // 返回值中有token，需要处理token
        // 将token保存在本地windows.localStorage  setItem(key, value) getItem(key)
        window.localStorage.setItem("token", res.data.access_token);

        // 在vuex中处理isLogin
        store.commit("setIsLogin", true);

        // 清空密码框中的内容
        userInfo.password = "";
        Toast.success("登录成功");
        setTimeout(() => {
          router.push({ path: "/home" });
        }, 1000);
      });
    };
    return {
      userInfo,
      onSubmit,
    };
  },
  components: {
    Navbar,
    [VanImage.name]: VanImage,
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    [Notify.name]: Notify,
    [Toast.name]: Toast,
  },
};
</script>

<style lang='less'>
.link-register {
  font-size: 14px;
  margin-bottom: 20px;
  color: #42b983;
  float: right;
  margin-right: 20px;
}
</style>